package snsdbook.engine.message;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import snsdbook.engine.FileManager;
import util.SQLUtil;
import util.Util;

public class UploadFileReply implements MessageInterface {

  private static final long serialVersionUID = -4325252208966784731L;
  private String filename_, id_, username_;
  private byte[] data_;
  private long timestamp_;
  
  public UploadFileReply(String username, String filename, String id,
                         byte[] data, long timestamp) {
    filename_ = filename;
    id_ = id;
    data_ = data;
    timestamp_ = timestamp;
    username_ = username;
  }
  
  @Override
  public String ProcessAsServer(ObjectInputStream is, ObjectOutputStream os) {
    
    String dbUrl = "jdbc:mysql://localhost/progin_171_13509096";
    String dbClass = "com.mysql.jdbc.Driver";
    String username = "progin";
    String password = "progin";
    
    try {
      Class.forName(dbClass);
      Connection con = DriverManager.getConnection(dbUrl, username, password);
    
      Util.Log("Deleting previous entry of new file, if any");
      SQLUtil.Modify("DELETE FROM files WHERE id_file='" + id_ + "'");
      
      Util.Log("Uploading new file to server...");
      // Prepare a statement to insert binary data
      String sql = "INSERT INTO files " +
                   "(username, filepath, data, timestamp, deleted) " +
                   "VALUES(?, ?, ?, ?, ?)";
      PreparedStatement pstmt = con.prepareStatement(sql);
      pstmt.setString(1, username_);
      pstmt.setString(2, filename_);
      pstmt.setBytes(3, data_);
      pstmt.setLong(4, timestamp_);
      pstmt.setInt(5, 0);
      
      Util.Log("Executing query for " + username_);
      
      pstmt.executeUpdate();
      Util.Log("File uploaded!");
      pstmt.close();
    } catch (ClassNotFoundException e) {
      Util.Fatal(e);
    } catch (SQLException e) {
      Util.Fatal(e);
    }
    
    return "";
  }

  @Override
  public String ProcessAsClient(ObjectInputStream is, ObjectOutputStream os,
      FileManager manager) {
    Util.Send(os, this);
    return "";
  }
  
  public String toString() {
    return "UPLOAD FILE REPLY, FILENAME=" + filename_ + ", ID=" + id_;
  }

}
